package register

import (
	"context"
	"sync"

	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/spf13/cobra"
)

type IApp interface {

	// 应用名称
	Name() string

	// 初始化
	Init(ctx context.Context) error
}

var (
	apps = make(map[string]IApp)
	lock = sync.Mutex{}
)

// 注册应用
func RegisterApp(app IApp) {
	lock.Lock()
	defer lock.Unlock()

	apps[app.Name()] = app
}

// 获取所有应用
func GetApps() []IApp {
	lock.Lock()
	defer lock.Unlock()

	var list []IApp
	for _, app := range apps {
		list = append(list, app)
	}
	return list
}

func GetAppsMiddleware() []middleware.Middleware {
	mids := make([]middleware.Middleware, 0)
	for _, app := range GetApps() {
		if t, ok := app.(ITransport); ok {
			mids = append(mids, t.GetHttpMiddlewares()...)
		}
	}

	return mids
}

func GetAppCommands() []*cobra.Command {
	var cmds []*cobra.Command
	for _, app := range GetApps() {
		if c, ok := app.(ICmdRegister); ok {
			cmds = append(cmds, c.GetCommands()...)
		}
	}
	return cmds
}
